﻿#include "ipwidget.h"
#include "ui_ipwidget.h"
#include <QUdpSocket>
#include <QSpinBox>
#include <QDebug>
#include <QRegularExpression>
IpWidget::IpWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::IpWidget)
{
    ui->setupUi(this);
    ui->label->adjustSize();
    QRegularExpression reg("spinBox_*");

     spins = this->findChildren<QSpinBox*>(reg);
    foreach(QSpinBox* box, spins){
        box->setButtonSymbols(QAbstractSpinBox::NoButtons);
        box->setAlignment(Qt::AlignCenter);
        connect(box,SIGNAL(valueChanged(int)),this, SLOT(onIPChanged(int)) );
    }
    setIP("127.0.0.1");
    setPort(7755);

    QUdpSocket udpsocket;

    udpsocket.writeDatagram("数据", 2, QHostAddress("192.168.101.42"), 16001);

    QByteArray ba;
    ba.append("发送的数据");
    udpsocket.writeDatagram(ba, QHostAddress("182.168.101.42"), 10061);
}

IpWidget::~IpWidget()
{
    delete ui;
}


void IpWidget::setPort(int port)
{
    if(m_port == port)return;
    m_port = port;
    ui->spinBox_port->setValue(m_port);
}

QString IpWidget::getIP()
{
    return m_ip;
}

int IpWidget::getPort()
{
	return m_port;
}

void IpWidget::onIPChanged(int i)
{
    QString newIP = QString::asprintf("%d.%d.%d.%d",
                                    ui->spinBox_1->value(),
                                    ui->spinBox_2->value(),
                                    ui->spinBox_3->value(),
                                    ui->spinBox_4->value());
    int newPort = ui->spinBox_port->value();
    if(newIP.compare(m_ip) || newPort!=m_port){
        m_ip = newIP;
        m_port = newPort;
        emit addressChanged(m_ip, m_port);
        qDebug()<< m_ip<<":"<<m_port;
    }
}

void IpWidget::setAddress(const QString &ip, int port)
{
    if(!ip.isEmpty()&& ip.compare(m_ip))
        setIP(ip);

    if(m_port != port)
        setPort(port);
}

void IpWidget::setIP(const QString &ip)
{
    if(0==m_ip.compare(ip))return;
    m_ip = ip;
    for(int i=0;i<4;++i){
        auto spinbox = spins[i];
        QString value = m_ip.split('.')[i];
        spinbox->setValue(value.toInt());
    }
    emit addressChanged(m_ip, m_port);
}
